using Tyng.Web.UI.Script;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI;

namespace Tyng.Web.UI.YUI
{
    public class Menu : Control
    {
        const string DefaultMenuType = "YAHOO.widget.Menu";
        internal const int DefaultHideDelay = 500;
        internal const int DefaultShowDelay = 100;

        public Menu() { }

        protected override ControlCollection CreateControlCollection()
        {
            return new EmptyControlCollection(this);
        }

        #region Properties
        [DefaultValue(false)]
        public bool LazyLoad
        {
            get
            {
                object o = ViewState["LazyLoad"];
                if (o == null)
                    return false;

                return (bool)o;
            }
            set
            {
                ViewState["LazyLoad"] = value;
            }
        }

        [DefaultValue(true)]
        public bool AutoSubmenuDisplay
        {
            get
            {
                object o = ViewState["AutoSubmenuDisplay"];
                if (o == null)
                    return true;

                return (bool)o;
            }
            set
            {
                ViewState["AutoSubmenuDisplay"] = value;
            }
        }

        [DefaultValue("")]
        public string RenderTarget
        {
            get
            {
                object o = ViewState["RenderTarget"];
                if (o == null)
                    return string.Empty;

                return (string)o;
            }
            set
            {
                ViewState["RenderTarget"] = value;
            }
        }

        [DefaultValue(DefaultMenuType)]
        public string MenuType
        {
            get
            {
                object o = ViewState["MenuType"];
                if (o == null)
                    return DefaultMenuType;

                return (string)o;
            }
            set
            {
                ViewState["MenuType"] = value;
            }
        }

        private MenuItemCollection _items = new MenuItemCollection();
        public MenuItemCollection MenuItems { get { return _items; } }

        #endregion

        #region Viewstate
        protected override void TrackViewState()
        {
            base.TrackViewState();

            ((IStateManager)_items).TrackViewState();
        }

        protected override void LoadViewState(object savedState)
        {
            if (savedState != null)
            {
                Pair p = (Pair)savedState;

                base.LoadViewState(p.First);

                ((IStateManager)_items).LoadViewState(p.Second);
            }
        }

        protected override object SaveViewState()
        {
            return new Pair(base.SaveViewState(), ((IStateManager)_items).SaveViewState());
        }

        #endregion

        protected override void Render(HtmlTextWriter writer)
        {
            //start script
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.WriteLine("<!-- ");

            //start function
            writer.WriteLine("d8.namespace('d8.yui.menu'); d8.yui.menu." + this.ClientID + " = function() {");
            writer.Write("var m = new " + this.MenuType + "(" + JavaScriptConvert.ToString(this.ClientID) + ", ");

            JsonSerializer json = new JsonSerializer();

            //TODO: centralize all these converter registrations...
            json.Converters.Add(new AlignmentJsonConverter());
            json.Converters.Add(new ContextAlignmentJsonConverter());

            json.Serialize(writer, this.CreateConfig());
            
            writer.WriteLine(");");

            if (string.IsNullOrEmpty(RenderTarget))
                writer.WriteLine("m.render(document.body);");
            else
                writer.Write("m.render(" + JavaScriptConvert.ToString(this.RenderTarget) + ");");

            writer.WriteLine("};");

            //attach function to window load
            writer.WriteLine("YAHOO.util.Event.addListener(window, 'load', d8.yui.menu." + this.ClientID + ");");

            //end script
            writer.Write("// -->");
            writer.RenderEndTag();
        }

        protected virtual Dictionary<string, object> CreateConfig()
        {
            Dictionary<string, object> config = new Dictionary<string, object>();

            config.Add("lazyload", this.LazyLoad);
            config.Add("id", this.ClientID);
            config.Add("itemdata", this.MenuItems);
            config.Add("autosubmenudisplay", this.AutoSubmenuDisplay);
            config.Add("hidedelay", DefaultHideDelay);
            config.Add("showdelay", DefaultShowDelay);

            return config;
        }
    }
}
